const db = wx.cloud.database()
Page({
  data: {
    accessToken: "",
    isShow: false,
    results: [],
    src: "",
    isCamera: true,
    btnTxt: "拍照"
  },

  accessTokenFunc: function () {
    var that = this
    db.collection('token').orderBy('refresh_time', 'desc').limit(1).get({
      success: function (res) {
        console.log(res.data[0])
        that.setData({
          accessToken: res.data[0].access_token
        })
      }
    })
  },
  
  onLoad() {
    this.accessTokenFunc()
    this.ctx = wx.createCameraContext()
  },

  takePhoto() {
    var that = this
    if (this.data.isCamera == false) {
      this.setData({
        isCamera: true,
        btnTxt: "拍照"
      })
      return
    }
    this.ctx.takePhoto({
      quality: 'normal',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          isCamera: false,
          btnTxt: "重拍"
        })
        wx.showLoading({
          title: '正在加载中',
        })
        wx.getFileSystemManager().readFile({
          filePath: res.tempImagePath,
          encoding: "base64",
          success: res => {
            console.log("图片读取成功")
            that.req(that.data.accessToken, res.data)
          },
          fail: res => {
            wx.hideLoading()
            wx.showToast({
              title: '拍照失败,未获取相机权限或其他原因',
              icon: "none"
            })
          }
        })
      }
    })
  },

  req: function (token, image) {
    var that = this
    // console.log("开始识别：" + token)
    var url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + token
    wx.request({
      url: url,
      data: {
        image: image
      },
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded",
      },
      success: function (res) {
      wx.hideLoading()
      //console.log(JSON.stringify(res))
      var num = res.result_num
      var results = res.data.result
      if (results != undefined && results != null) {
        that.setData({
          isShow: true,
          results: results
        })

        console.log(results)
      } else {
        wx.showToast({
          icon: 'none',
          title: 'AI识别失败,请联系管理员',
        })
      }
    }})
  },

  radioChange: function (e) {
    console.log(e.detail.value)
  },

  hideModal: function () {
    this.setData({
      isShow: false,
    })
  },
})